package com.talios.jira.settings.projects;

import com.intellij.openapi.ui.DialogBuilder;
import com.intellij.openapi.ui.DialogWrapper;
import com.talios.jira.browser.JiraProjectDetails;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SimpleProjectSettings implements ProjectSettings {
    private JButton cancel;
    private JButton apply;
    private JTextField componentId;
    private JPanel mainPanel;

    private boolean changed;
    private JTextField projectId;
    private JiraProjectDetails project;
    private DialogWrapper dialog;
    private String title;

    public SimpleProjectSettings(final JiraProjectDetails project, String title) throws HeadlessException {
        this.project = project;
        this.title = title;

        apply.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                storeValuesTo(project);
                dialog.close(0);
            }
        });

        cancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dialog.close(-1);
            }
        });

    }

    public boolean editProject(DialogWrapper owner) {
        DialogBuilder db = new DialogBuilder(owner.getContentPane());

        dialog = db.getDialogWrapper();
        dialog.setSize(350, 125);
        dialog.setTitle(title);
        dialog.setModal(true);
        dialog.getContentPane().add(mainPanel);

        changed = false;

        loadValuesFrom(project);

        dialog.show();

        return changed;
    }

    private void storeValuesTo(JiraProjectDetails project) {
        changed = !projectId.getText().equals(project.getProjectId()) || !componentId.getText().equals(project.getComponentId());

        project.setProjectId(projectId.getText());
        project.setComponentId(componentId.getText());
    }

    private void loadValuesFrom(JiraProjectDetails project) {
        projectId.setText(project.getProjectId());
        componentId.setText(project.getComponentId());
    }


}
